package com.yc.admin.controller.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yc.common.constant.Constant;
import com.yc.common.core.domain.AjaxResult;
import com.yc.system.service.IEmailCodeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@Api("邮箱验证码")
public class EmailCodeController {
    
    @Autowired
    @Qualifier("emailCodeConsumerService")
    private IEmailCodeService emailCodeService;

    /**
     * 接收用户发送验证码请求
     * @param requestBody 邮箱地址
     * @return 响应结果
     */
    @PostMapping("/email-code")
    @ApiOperation("发送邮箱验证码")
    public AjaxResult sendCode(@RequestBody String requestBody) {

        AjaxResult ajax = AjaxResult.success();

        try {
            // 使用 Jackson 解析 JSON 请求体
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, String> requestMap = objectMapper.readValue(requestBody, Map.class);

            String email = requestMap.get("email");
            System.out.println(email);

            // 参数校验
            if (email == null || email.isEmpty()) {
                return AjaxResult.error("请输入邮箱！");
            }

            emailCodeService.sendEmailCode(email);
            return ajax.put("msg", "验证码已发送，请注意查收！");
        } catch (Exception e) {
            return AjaxResult.error(Constant.HttpStatus.FAIL, "发送失败，请重新发送！");
        }
    }

    /**
     * 接收用户验证验证码请求
     * @param request 包含邮箱地址和验证码的请求数据 {"email": "user@example.com", "code": "123456"}
     * @return 响应结果
     */
    @PostMapping("/verify-code")
    @ApiOperation("验证邮箱验证码")
    public AjaxResult verifyCode(@RequestBody Map<String, String> request) {

        AjaxResult ajax = AjaxResult.success();

        String email = request.get("email");
        String code = request.get("code");

        // 参数校验
        if (email == null || email.isEmpty()) {
            return AjaxResult.error("邮箱不能为空!");
        }
        if (code == null || code.isEmpty()) {
            return AjaxResult.error("验证码不能为空!");
        }

        //验证码校验
        boolean isValid = emailCodeService.verifyCode(email, code);

        if (isValid) {
            return ajax.put("msg", "验证成功！");
        } else {
            return AjaxResult.error("验证码过期，请重新发送！");
        }
    }
} 